<template>
	<uv-navbar :fixed="true" :placeholder="true" :title="title" left-arrow @leftClick="$onClickLeft" />
	<view class="order-container">
		<uv-form labelPosition="left" :model="showForm" :rules="rules" ref="formRef" :labelStyle="{marginLeft: '18px'}">
			<uv-form-item label="电站名称" prop="queryObj.powerstationId"
				@click="isDisabled ? showSelect('powerstationId') : null" :labelWidth="labelWidth" borderBottom
				labelAlign="right" :disabled="true">
				<uv-input v-model="showForm.queryObj.powerstationName" border="none" placeholder="请选择"
					disabled></uv-input>

				<uv-picker ref="powerstationIdRef" :columns="actionOption.stationOption" :closeOnClickOverlay="false"
					keyName="name" @confirm="handlePickerConfirm" @close="handlePickerCancel"></uv-picker>
			</uv-form-item>
			<uv-form-item label="设备类型" prop="queryObj.deviceType" :labelWidth="labelWidth" borderBottom
				@click="isDisabled ? showSelect('deviceType') : null">

				<uv-input v-model="showForm.queryObj.deviceTypeName" border="none" placeholder="请选择"
					disabled></uv-input>
				<uv-picker ref="deviceTypeRef" :columns="actionOption.eqTypeOption" :closeOnClickOverlay="false"
					keyName="name" @confirm="eqTypeChange"></uv-picker>
			</uv-form-item>


			<uv-form-item label="设备" prop="queryObj.deviceId" :labelWidth="labelWidth" borderBottom
				@click="isDisabled ? showSelect('equipment') : null">
				<uv-input v-model="showForm.queryObj.deviceName" border="none" placeholder="请选择" disabled></uv-input>
				<uv-picker ref="equipmentRef" :columns="actionOption.equipmentOption" :closeOnClickOverlay="false"
					keyName="name" @confirm="eqChange"></uv-picker>

			</uv-form-item>

			<uv-form-item label="告警" prop="queryObj.alarmId" :labelWidth="labelWidth" borderBottom
				@click="isDisabled ? showSelect('alarmId') : null">

				<uv-input v-model="showForm.queryObj.alarmName" border="none" placeholder="请选择" disabled></uv-input>
				<uv-picker ref="alarmIdRef" :columns="actionOption.alarmOption" :closeOnClickOverlay="false"
					keyName="name" @confirm="alarmChange"></uv-picker>

			</uv-form-item>
			<uv-form-item label="优先级" prop="queryObj.priorityName" :labelWidth="labelWidth" borderBottom
				@click="showSelect('priority')">
				<uv-input v-model="showForm.queryObj.priorityName" border="none" placeholder="请选择" disabled></uv-input>
				<uv-picker ref="priorityRef" :columns="actionOption.priorityOption" :closeOnClickOverlay="false"
					keyName="name" @confirm="priorityChange"></uv-picker>
			</uv-form-item>

			<uv-form-item label="计划处理开始时间" prop="queryObj.handleDateRange" :labelWidth="labelWidth" borderBottom
				@click="showDateSelect('startTime')">

				<uv-datetime-picker ref="startDatetimeRef" mode="datetime" v-model="showForm.queryObj.planStartTime"
					@confirm="confirm"></uv-datetime-picker>
				<view v-if="showStartTime">{{showForm.queryObj.planStartTime}}</view>
				<view v-else>请选择时间</view>

				<template v-slot:right>
					<uv-icon name="arrow-right"></uv-icon>
				</template>
			</uv-form-item>
			<uv-form-item label="计划处理结束时间" prop="queryObj.handleDateRange" :labelWidth="labelWidth" borderBottom
				@click="showDateSelect('endTime')">


				<uv-datetime-picker ref="endDatetimeRef" mode="datetime" v-model="showForm.queryObj.planEndTime"
					@confirm="endConfirm"></uv-datetime-picker>
				<view v-if="showEndTime">{{showForm.queryObj.planEndTime}}</view>
				<view v-else>请选择时间</view>
				<template v-slot:right>
					<uv-icon name="arrow-right"></uv-icon>
				</template>
			</uv-form-item>

			<uv-form-item label="工单名称" prop="queryObj.title" :labelWidth="labelWidth" borderBottom>

				<uv-input placeholder="请输入内容" border="surround" v-model="showForm.queryObj.title"></uv-input>
			</uv-form-item>
			<uv-form-item label="工单模版" prop="queryObj.templateId" :labelWidth="labelWidth" borderBottom
				@click="showSelect('orderTemplate')">

				<uv-input v-model="showForm.queryObj.templateName" border="none" placeholder="请选择" disabled></uv-input>
				<uv-picker ref="templateIdRef" :columns="actionOption.templateOption" :closeOnClickOverlay="false"
					keyName="name" @confirm="templateChange"></uv-picker>
			</uv-form-item>

			<uv-form-item label="操作描述" prop="queryObj.description" :labelWidth="labelWidth" borderBottom>
				<uv-textarea v-model="showForm.queryObj.description" placeholder="请输入内容"></uv-textarea>
			</uv-form-item>

			<uv-form-item label="图片" prop="queryObj.fileInfoList" :labelWidth="labelWidth" borderBottom>
				<uv-upload :fileList="fileList" name="1" multiple :maxCount="9" @afterRead="afterRead"
					@delete="deletePic" :previewFullImage="true"></uv-upload>
			</uv-form-item>

			<uv-form-item label="发起人" prop="queryObj.promoter" :labelWidth="labelWidth" borderBottom
				@click="showSelect('promoterName')">
				<uv-input v-model="showForm.queryObj.promoter" disabled disabledColor="#ffffff" placeholder="发起人"
					border="none">
				</uv-input>
				<template v-slot:right>
					<uv-icon name="arrow-right"></uv-icon>
				</template>
			</uv-form-item>


			<uv-form-item label="处理人" prop="queryObj.processorId" :labelWidth="labelWidth" borderBottom>
				<customthree-tree-select class="cus1" search :listData="listData" :showChildren="false" lazyLoadChildren
					:load="loadNode" dataLabel="label" @select-change="handleSelect" @change="handleChange"
					v-model="showForm.queryObj.processorId" />
			</uv-form-item>


			<uv-form-item label="验证人" prop="queryObj.validatorId" :labelWidth="labelWidth" borderBottom>
				<customthree-tree-select class="cus2" search :listData="listData2" :showChildren="false"
					:load="loadNode" dataLabel="label" @select-change="handleSelect2" @change="handleChange2"
					lazyLoadChildren v-model="showForm.queryObj.validatorId" />

			</uv-form-item>
			<uv-button type="primary" text="提交" customStyle="margin-top: 10px" @click="submit"></uv-button>
			<uv-button type="info" text="重置" customStyle="margin-top: 10px" @click="reset"></uv-button>

		</uv-form>

	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		onMounted
	} from "vue"
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app"
	import {
		reqEqList,
		reqQueryList,
	} from "@/api/model/photovoltaic"
	import {
		reqStorageList
	} from "@/api/model/storageEnergy"
	import {
		VUE_APP_UPLOAD_URL
	} from '@/config';

	import {
		formatDateTime
	} from '@/utils/util'
	import {
		reqWorkTemplateList,
		reqSubmitWorkTemplate
	} from "@/api/operate"
	import {
		reqPVAlarm
	} from "@/api/alarm"
	import {
		getCurrentInstance
	} from 'vue';
	import {
		reqWindStationList,
		reqWindBoardList,
		reqWindDeviceType,
		reqWindDeivceList
	} from "@/api/model/windEnergy"
	import {
		reqStorageNoList
	} from "@/api/model/storageEnergy.js"
	import {
		reqUserTree,
		reqDeptTree,
		reqOrgTree,
	} from "@/api/system"
	import {
		reqUserPage
	} from "@/api/user.js"
	import {
		reqUpload
	} from "@/api/common"
	import DaTree from '@/components/da-tree/index.vue'

	import CustomPicker from "@/components/cus-picker/CusPicker"
	// import CustomTreeSelect from "@/components/customTreeSelect"
	const title = ref('新建工单')


	const labelWidth = ref('95')
	const isDisabled = ref(true)
	const showStartTime = ref(false)
	const showEndTime = ref(false)
	const currentModule = ref(null)
	const formRef = ref(null)
	let dateRange = ref(null)
	const powerstationIdRef = ref(null)
	const deviceTypeRef = ref(null)
	const alarmIdRef = ref(null)
	const priorityRef = ref(null)
	const equipmentRef = ref(null)
	const templateIdRef = ref(null)
	const actionOption = reactive({
		stationOption: [],
	})

	const startDatetimeRef = ref(null)
	const endDatetimeRef = ref(null)
	const testIndex = ref(0)
	const form = reactive({
		queryObj: {
			title: '',
		},
	})
	const instance = getCurrentInstance()
	//展示表单form
	const showForm = reactive({
		queryObj: {
			deviceName: '',
			planStartTime: Number(new Date()),
			planEndTime: Number(new Date()),
			processorId: '', //处理人
			validatorId: '', //验证人
		}
	})
	const mapKey = ref('')
	const rules = reactive({
		'queryObj.powerstationId': {
			type: 'string',
			required: true,
			message: '请选择电站'
		},
		'queryObj.deviceType': {
			required: true,
			message: '请选择设备类型'
		},
		'queryObj.deviceId': { // 注意字段名改为 deviceId
			required: true,
			message: '请选择设备'
		},
		'queryObj.priority': {
			required: true,
			message: '请选择优先级'
		},
		'queryObj.planStartTime': {
			required: true,
			message: '请选择开始时间'
		},
		'queryObj.planEndTime': {
			required: true,
			message: '请选择结束时间'
		},
		'queryObj.title': {
			required: true,
			message: '请输入工单名称'
		},
		'queryObj.templateId': {
			required: true,
			message: '请选择工单模版'
		},
		'queryObj.description': {
			required: true,
			message: '请输入操作描述'
		}
	})

	const fileList = ref([])
	const listData = ref([])
	const listData2 = ref([])


	const handleChange = (e) => {
		if (e.show) {
			getOrgUser('processor');
		}
	}
	const handleChange2 = (e) => {
		if (e.show) {
			getOrgUser('validator');
		}
	}
	const loadNode = (node) => {
		// console.log(node, "999");
		return new Promise((resolve) => {
			let query = {
				"isPagination": false,
				"orderBy": "created_time desc",
				"pageNum": 1,
				"pageSize": 100,
				"queryObj": {
					"deptId": node.id
				}
			}
			reqUserPage(query).then((res) => {
				let data = res.data.data.list.map((item) => {
					return {
						label: item.nickName,
						id: item.userId,
					};
				});
				if (data.length > 0) {
					resolve(data);
				} else {
					resolve([]);
				}

			})

		})
	}
	//获取组织数和人员
	const getOrgUser = async (type) => {
		try {
			let res = await reqOrgTree({})
			if (type == 'processor') {
				listData.value = res.data.data
			} else if (type == 'validator') {
				listData2.value = res.data.data
			}
		} catch (error) {
			console.error(error);
		}
		// console.log("公司树", listData.value)
	}
	//选中
	const handleSelect = (selected) => {
		// showForm.queryObj.processorId = selected.id;
		// showForm.queryObj.processorName = selected.label;
	}
	const handleSelect2 = (selected) => {
		// showForm.queryObj.validatorId = selected.id;
		// showForm.queryObj.verifierName = selected.label;
	}
	// 提交
	const submit = async () => {
		try {
			// 1. 表单验证
			await formRef.value.validate();
			// 2. 处理数据格式
			const submitData = {
				...showForm,
				processorId: Array.isArray(showForm.processorId) ?
					showForm.processorId.join(',') : showForm.processorId,
				validatorId: Array.isArray(showForm.validatorId) ?
					showForm.validatorId.join(',') : showForm.validatorId
			};

			// 3. 提交数据
			// console.log("提交参数==》", submitData.queryObj)
			const response = await reqSubmitWorkTemplate(submitData.queryObj);


			// 4. 成功反馈
			uni.showToast({
				icon: 'success',
				title: '提交成功',
				duration: 1500
			});

			// 5. 返回上一页
			setTimeout(() => uni.navigateBack(), 1500);

		} catch (error) {
			console.error("提交失败:", error);

			// 6. 错误处理
			const errorMsg = error.message || '提交失败，请检查表单';
			uni.showToast({
				icon: 'none',
				title: errorMsg,
				duration: 2000
			});
		}
	}

	const bindPickerChange = (e) => {
		console.log('picker发送选择改变，携带值为', e.detail.value)
		testIndex.value = e.detail.value

	}
	const afterRead = async (event) => {
		// console.log("event.file===", event)
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = Array.isArray(event.file) ? event.file : [event.file];
		let fileListLen = fileList.value.length;
		lists.forEach((item) => {
			fileList.value.push({
				...item,
				status: 'uploading',
			});
			// message: '上传中'
		});

		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url, lists);
			console.log("返回结果", result)
			let item = fileList.value[fileListLen];
			fileList.value[fileListLen] = {
				...item,
				status: 'success',
				message: '',
				url: result
			};
			fileListLen++;

		}
	}

	const uploadFilePromise = (url, files) => {
		let file = files[0]
		return new Promise((resolve, reject) => {
			let fileName = file.name
			// 将 Blob 转换为 File 对象
			const newFile = new File([file.url], fileName, {
				type: file.type
			});
			let formdata = new FormData();
			formdata.append("file", newFile);
			reqUpload(formdata).then(response => {
				resolve(response.data.url)
			})
		})
	}
	const deletePic = (e) => {
		fileList.value.splice(e.index, 1);
		formRef.value.validateField('pics', err => {
			// 处理错误后的逻辑
		})
	}
	// 重置
	const reset = () => {
		formRef.value.resetFields();
		formRef.value.clearValidate();
		showForm.queryObj = {
			deviceName: '',
			planStartTime: Number(new Date()),
			planEndTime: Number(new Date())
		}
	}

	//回写发起人
	const getPromoter = () => {
		let {
			userName
		} = uni.getStorageSync('zh-h5-userInfo')
		showForm.queryObj.promoter = userName

	}
	//通用下拉选择框
	const showSelect = (val) => {
		mapKey.value = val
		const map = {
			'powerstationId': powerstationIdRef,
			'deviceType': deviceTypeRef,
			'alarmId': alarmIdRef,
			'priority': priorityRef,
			'equipment': equipmentRef,
			'orderTemplate': templateIdRef
		}
		map[val].value.open()
		getOption(val)
		// hideKeyboard();
	}
	//根据选择返回对应下拉框的值
	const getOption = async (val) => {
		try {
			switch (val) {
				case 'powerstationId':
					return await handlePowerStationOptions();
					// case 'deviceType':
					// 	return await handleDeviceTypeOptions();
				case 'equipment':
					return await handleEquipmentOptions();

				case 'priority':
					actionOption.priorityOption = [
						[{
								name: "较低",
								value: 0,
							},
							{
								name: "普通",
								value: 1,
							},
							{
								name: "紧急",
								value: 2,
							},
							{
								name: "非常紧急",
								value: 3,
							},
						]
					]
					return;
				case 'orderTemplate':
					let query = {
						"isPagination": false,
						"orderBy": "create_time desc",
						"queryObj": {
							"isBasic": "",
							"flagn": 1
						}
					}
					let res = await reqWorkTemplateList(query)
					actionOption.templateOption = [res.data.data.list]
					return;

				default:
					return;
			}

		} catch (error) {
			throw error;
		}
	}
	// 处理电站选项
	const handlePowerStationOptions = async () => {
		let response;
		switch (currentModule.value) {
			case '1':
				response = await fetchAndMapData(reqWindBoardList, 'stationName', 'id');
				break;
			case '3':
				response = await fetchAndMapData(reqStorageNoList, 'stationName', 'id');
				break;
			case '2':
				response = await fetchAndMapData(reqQueryList, 'name', 'id');
				break;
			default:
				break;
		}
		actionOption.stationOption = [response];
	}
	//设备类型下拉选项
	const handleDeviceTypeOptions = async () => {
		if (currentModule.value == 1) {
			const response = await fetchAndMapData(reqWindDeviceType, 'blowerName', 'blowerCode');
			actionOption.eqTypeOption = [response];
		} else if (currentModule.value == 2 || currentModule.value == 5) { //光伏/传统能耗

			return;
		} else if (currentModule.value == 3) { //储能

		}

	}
	// 处理设备选项
	const handleEquipmentOptions = async () => {
		if (currentModule.value == 2) {
			let {
				data
			} = await reqEqList(showForm.queryObj.deviceType, showForm.queryObj.powerstationId)
			actionOption.equipmentOption = [data.data]
		}

	}
	// 通用数据获取和映射函数
	const fetchAndMapData = async (apiFn, nameKey, valueKey) => {
		const {
			data
		} = await apiFn();
		console.log("设备选项--》", data)

		return data.data.map(item => ({
			name: item[nameKey],
			value: item[valueKey] || item.id // 提供后备值
		}));


	}
	const fetchListAndMapData = async (apiFn, nameKey, valueKey) => {
		const {
			data
		} = await apiFn();
		console.log("设备选项--》", data)

		return data.data.list.map(item => ({
			name: item[nameKey],
			value: item[valueKey] || item.id // 提供后备值
		}));
	}
	//根据电站获取对应设备类型（风机）
	const getDeviceTyepeByStation = async (val) => {
		let params = {
			blowerName: val
		}
		let {
			data
		} = await reqWindDeviceType(params)
		let resultData = data.data.map(item => ({
			...item,
			name: item.blowerName
		}))
		actionOption.eqTypeOption = [resultData]

	}
	//根据电站和设备类型返回设备
	const getDeviceByStationAndType = async (stationName, deviceTypeName) => {
		let params = {
			"stationName": stationName,
			"blowerName": deviceTypeName
		}
		//切换为不分页接口（跟后端说）
		let {
			data
		} = await reqWindDeivceList(params);
		let resultData = data.data.list.map(item => ({
			...item,
			name: item.deviceName
		}))
		actionOption.equipmentOption = [resultData];
	}
	// Picker 确认事件
	const handlePickerConfirm = ({
		value
	}) => {
		const selectedCity = value[0]; // 获取第一个选中的对象
		showForm.queryObj.powerstationId = selectedCity.value;
		showForm.queryObj.powerstationName = selectedCity.name;

		showForm.queryObj.deviceTypeName = ''
		showForm.queryObj.deviceType = ''

		showForm.queryObj.deviceName = ''
		showForm.queryObj.deviceId = ''
		switch (currentModule.value) {
			case '1':
				getDeviceTyepeByStation(selectedCity.name);
				return;
			case '2':
			case '5':
				actionOption.eqTypeOption = [
					[{
						value: 'equipment_inverter',
						name: '逆变器'
					}]
				];
			case '3':
				actionOption.eqTypeOption = [
					[{
							value: "0",
							name: "电池系统",
						},
						{
							value: "1",
							name: "pcs系统",
						},
						{
							value: "2",
							name: "消防系统",
						},
						{
							value: "3",
							name: "辅助系统",
						},
					]
				]
		}


		console.log("电站ID", value)
	};
	const handlePickerCancel = () => {
		console.log('关闭:'); // 输出选中的对象
	}

	//展开计划处理时间选择
	const showDateSelect = (val) => {
		console.log("日期的", val)
		switch (val) {
			case 'startTime':

				startDatetimeRef.value.open();
				return;
			case 'endTime':

				endDatetimeRef.value.open();
				return;
		}
	}

	// 日期确认按钮
	const confirm = async (e) => {
		let time = await formatDateTime(e.value)
		showStartTime.value = true
		showForm.queryObj.planStartTime = time
	}
	const endConfirm = async (e) => {
		let time = await formatDateTime(e.value)
		showEndTime.value = true
		showForm.queryObj.planEndTime = time
	}
	/**
	 * 电站change事件
	 */
	const stationChange = async (e) => {
		showForm.queryObj.powerstationId = e
	}
	//设备类型切换
	const eqTypeChange = async ({
		value
	}) => {
		console.log("e----", value)
		showForm.queryObj.deviceTypeName = value[0].name
		showForm.queryObj.deviceType = value[0].value

		showForm.queryObj.deviceName = ''
		showForm.queryObj.deviceId = ''

		if (currentModule.value == 3) { //储能
			getStroageDeviceList()
		} else if (currentModule.value == 1) { //风机
			getDeviceByStationAndType(showForm.queryObj.powerstationName, showForm.queryObj.deviceTypeName)
		} else {

			let {
				data
			} = await reqEqList(value.value, showForm.queryObj.powerstationId)
			actionOption.equipmentOption = [data.data]
		}

	}
	const eqChange = async ({
		value
	}) => {
		console.log("value===", value)
		showForm.queryObj.deviceId = value[0].id || value[0].value
		showForm.queryObj.deviceName = value[0].name
		let query = {
			"isPagination": false,
			"orderBy": "create_time desc",
			"queryObj": {
				"equipment": value[0].id,
				"alState": 1,
				"dzId": showForm.powerstationId
			}
		}

		let {
			data
		} = await reqPVAlarm(query)
		actionOption.alarmOption = data.data.list

	}
	// 
	const alarmChange = ({
		value
	}) => {
		showForm.queryObj.alarmId = value[0].id
		showForm.queryObj.alarmName = value[0].name
		// console.log("告警==", e, showForm.powerstationId)
	}
	const priorityChange = ({
		value
	}) => {
		showForm.queryObj.priority = value[0].value
		showForm.queryObj.priorityName = value[0].name
	}
	const templateChange = ({
		value
	}) => {
		console.log("模版===", value)
		showForm.queryObj.templateId = value[0].id
		showForm.queryObj.templateName = value[0].name
	}

	//获取储能设备
	const getStroageDeviceList = async () => {
		let query = {
			owningSystem: showForm.queryObj.deviceType,
			stationId: showForm.queryObj.powerstationId
		}
		let res = await reqStorageList(query);
		let deviceList = res.data.data.list.map(item => {
			return {
				name: item.deviceName,
				value: item.id
			}
		})
		actionOption.equipmentOption = [deviceList]
	}
	const hideKeyboard = () => {
		uni.hideKeyboard()
	}

	onMounted(() => {
		getPromoter()
		getOrgUser('processor')
	})

	onLoad((options) => {
		console.debug('创建工单---:', options);
		try {
			// 1. 安全解析传入参数
			const detailData = options?.detailData ? JSON.parse(options.detailData) : null;
			// 2. 获取并记录当前模块

			// console.debug('当前模块:', currentModule, '页面参数:', options);
			// 3. 处理回显数据逻辑
			if (detailData) {
				isDisabled.value = false;
				// 使用对象解构赋值
				const {
					powerStation,
					eqType,
					name,
					equipment
				} = detailData;
				// 集中设置表单值
				Object.assign(showForm.queryObj, {
					powerstationName: powerStation,
					deviceTypeName: eqType,
					alarmName: name,
					deviceName: equipment
				});
				console.debug('表单回显数据:', showForm.queryObj);
			}



		} catch (error) {
			console.error('页面加载失败:', error);
			uni.showToast({
				title: '页面初始化失败',
				icon: 'none'
			});
			// 可选：跳转到错误页面或回退
			// uni.navigateBack();
		}

	})
	onShow(() => {
		const localCurrentModule = uni.getStorageSync('zh-h5-select-module');
		currentModule.value = localCurrentModule
	})
</script>

<style lang="scss" scoped>
	.order-container {
		.uv-form {
			::v-deep {
				.uv-form-item__body {
					padding: 10px;
				}

				.select-list {
					width: 100%;
				}
			}
		}
	}
</style>